package com.klm.datakeeper;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.klm.datakeeper.filemonitoring.FileModificationService;
import com.klm.datakeeper.filemonitoring.FileModificationService.FileModificationServiceBinder;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class EditFilePathsActivity extends Activity {
	
	private static final int REQUEST_PICK_FILE = 1;
	private SharedPreferences filePathsPreferences;
	private int amountOfFilePaths;
	private List<HashMap<String,String>> listViewItems;
	private SimpleAdapter listViewAdapter;
	private FileModificationService fileModificationService;
	private boolean isBound = false;
	
	// Keys used in Hashmap
    private static final String[] FROM = { "icon","name","path" };
    // Ids of views in listview_layout
    private static final int[] TO = { R.id.icon, R.id.name, R.id.path};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_file_paths_activity);
		
		filePathsPreferences = getSharedPreferences(AppConstants.FILE_PATHS_OBSERVER_PREFERENCES, MODE_PRIVATE);
		
		ArrayList<File> filesList = new ArrayList<File>();
		
		int i = 0;
		while(filePathsPreferences.getString(AppConstants.FILE_PATH_PREFS_KEY + i, null) != null){
			String path = filePathsPreferences.getString(AppConstants.FILE_PATH_PREFS_KEY + i, null);
			File file = new File(path);
			filesList.add(file);
			i++;
		}
		amountOfFilePaths = i;
	    
	 // Each row in the list stores country name, currency and flag
        listViewItems = new ArrayList<HashMap<String,String>>();
 
        for(File file : filesList){
            listViewItems.add(getHashMapListViewItem(file));
        }
        

        listViewAdapter = new SimpleAdapter(getBaseContext(), listViewItems, R.layout.list_view_item_row, FROM, TO);
		
		ListView listview = (ListView) findViewById(R.id.file_paths_listview);
		
		listview.setAdapter(listViewAdapter);
		
		Button addButton = (Button) findViewById(R.id.add_file_path_button);
		addButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(EditFilePathsActivity.this, FilePickerActivity.class);
				
				// Set the initial directory to be the sdcard
				intent.putExtra(FilePickerActivity.EXTRA_FILE_PATH, Environment.getExternalStorageDirectory().getAbsolutePath());
				
				startActivityForResult(intent, REQUEST_PICK_FILE);
			}
			
		});
	}
	
	@Override
	protected void onStart() {
		bindToFileModificationService();
		super.onStart();
	}
	
	@Override
	protected void onStop() {
		if(isBound){
			unbindService(serviceConnection);
			isBound = false;
		}
		super.onStop();
	}
	
	@Override
	protected void onPause() {
		if(isBound){
			unbindService(serviceConnection);
			isBound = false;
		}
		super.onPause();
	}
	
	private void bindToFileModificationService(){
		Intent intent = new Intent(getApplicationContext(), FileModificationService.class);
		bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
	}
	
	@Override
	protected void onResume() {
		if(!isBound){
			bindToFileModificationService();
		}
		super.onResume();
	}
	
	private ServiceConnection serviceConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			FileModificationServiceBinder binder = (FileModificationServiceBinder) service;
			fileModificationService = binder.getService();
			isBound = true;
			
		}
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			isBound = false;
		}
		
	};
	
	private HashMap<String, String> getHashMapListViewItem(File file){
		HashMap<String, String> hashMapListViewItem = new HashMap<String,String>();
        hashMapListViewItem.put("name", "Name: " + file.getName());
        hashMapListViewItem.put("path", "Path: " + file.getAbsolutePath());
        if(file.isDirectory())
        	hashMapListViewItem.put("icon", String.valueOf(R.drawable.folder_blue));
        else
        	hashMapListViewItem.put("icon", String.valueOf(R.drawable.document_yellow));
        return hashMapListViewItem;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == RESULT_OK) {
			switch(requestCode) {
			case REQUEST_PICK_FILE:
				if(data.hasExtra(FilePickerActivity.EXTRA_FILE_PATH)) {
					// Get the file path
					File file = new File(data.getStringExtra(FilePickerActivity.EXTRA_FILE_PATH));
					Toast.makeText(getApplicationContext(), file.getAbsolutePath(), Toast.LENGTH_LONG).show();
					Editor filePathsPreferencesEditor = filePathsPreferences.edit();
					filePathsPreferencesEditor.putString(AppConstants.FILE_PATH_PREFS_KEY + amountOfFilePaths, file.getAbsolutePath());
					filePathsPreferencesEditor.commit();
					listViewItems.add(getHashMapListViewItem(file));
					listViewAdapter.notifyDataSetChanged();
					
					fileModificationService.createFileObserver(file);
				}
			}
		}
	}

}
